package com.wuad.platformwuad.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuad.platformwuad.module.system.entity.LoginUser;
import com.wuad.platformwuad.module.system.entity.SysUserEntity;
import com.wuad.platformwuad.module.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 *
 * 注意：控制台没有输出默认的密码是因为service类 实现了UserDetailsService接口, 并重写了UserDetails方法的原因
 *
 * @author wuad
 * @date 2023年08月11日 17:00
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<SysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserEntity::getUserName,username);
        SysUserEntity sysUserEntity = userMapper.selectOne(wrapper);
        //如果查询不到数据(没有当前用户)就通过抛出异常来给出提示
        if(Objects.isNull(sysUserEntity)){
            log.info("用户名或密码错误");
            throw new RuntimeException("用户名或密码错误");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中
        //封装成UserDetails对象返回
        return new LoginUser(sysUserEntity);
    }

}
